package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Product;
import com.example.demo.mapper.ProductMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/product")
public class ProductController extends BaseController {
    @Resource
    ProductMapper productMapper;
    @PostMapping
    public Result<?> save(@RequestBody Product product)
    {
        if(product.getIntroduction()==null){
            product.setIntroduction("暂无简介");
        }
        productMapper.insert(product);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody Product product)
    {
        productMapper.updateById(product);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Integer id)
    {
        productMapper.deleteById(id);
        return Result.success();
    }


    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<Product> wrapper = Wrappers.<Product>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Product::getName, search);
        }
        Page<Product> BookPage = productMapper.findPage(new Page<>(pageNum, pageSize),search);
        return Result.success(BookPage);
    }

}
